import numpy as np
import cv2 as cv
import time
import os
import socket



cam_width=800
cam_height=448

cap = cv.VideoCapture(2)


cv.namedWindow("left")
cv.moveWindow("left", 40, 80)

if not cap.isOpened():
    print("Cannot capture from camera. Exiting.")
    os._exit(1)
last_time = time.time()

fourcc = cv.VideoWriter_fourcc(*'XVID')    # 视频存储的格式
fps = cap.get(cv.CAP_PROP_FPS)   # 帧率
size = (int(cap.get(cv.CAP_PROP_FRAME_WIDTH)), \
        int(cap.get(cv.CAP_PROP_FRAME_HEIGHT))) 
# 文件名设置                 
filename = '/home/pi/camera/Video/video_'+ \
    time.strftime("%Y%m%d_%H%M%S", time.localtime())+'.avi'
out = cv.VideoWriter(filename, fourcc, fps, size)  # 视频存储

address = ('192.168.151.15', 12000)
#address = ('192.168.1.98', 12000)

try:
    #建立socket对象
    #socket.AF_INET：服务器之间网络通信 
	#socket.SOCK_STREAM：流式socket , for TCP
    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    	#开启连接
    sock.connect(address)
except socket.error as msg:
    print(msg)
    os._exit(1)

#压缩参数，后面cv2.imencode将会用到，对于jpeg来说，15代表图像质量，越高代表图像质量越好为 0-100，默认95
encode_param=[int(cv.IMWRITE_JPEG_QUALITY),95]
ret, frame = cap.read()
while(True):

    #cv.imshow('left', frame)
	#cv2.imencode将图片格式转换(编码)成流数据，赋值到内存缓存中;主要用于图像数据格式的压缩，方便网络传输
	#'.jpg'表示将图片按照jpg格式编码。
    result, imgencode = cv.imencode('.jpg', frame, encode_param)
	#建立矩阵
    data = np.array(imgencode)
	#将numpy矩阵转换成字符形式，以便在网络中传输
    stringData = data.tostring()
		
	#先发送要发送的数据的长度
	#ljust() 方法返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串
    sock.send(str.encode(str(len(stringData)).ljust(16)));
	#发送数据
    sock.send(stringData);
	#读取服务器返回值
    #receive = sock.recv(1024)
    #if len(receive):print(str(receive,encoding='utf-8'))

    ret, frame = cap.read()

sock.close()
cap.release()

